package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.MyUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;




/**
 * 交通 信息操作处理
 *
 * @author ruoyi
 * @date 2019-03-21
 */
@Controller
@RequestMapping("/system/jiaotong")
public class JiaotongController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysProfileController.class);

    private String prefix = "system/jiaotong";


    @Autowired
    private MyWebScoketController websc;
    @Autowired
    private IJiaotongService jiaotongService;
    @Autowired
    private ILvyouService lvyouService;

    @Autowired
    private IZhengquService zhengquService;

    @Autowired
    private IShuixiService shuixiService;

    @Autowired
    private IZongheService zongheService;

    @Autowired
    private ISysCategoryService categoryService;


    @RequiresPermissions("system:jiaotong:view")
    @GetMapping()
    public String jiaotong() {
        return prefix + "/jiaotong";
    }

    /**
     * 查询交通列表
     */
    @RequiresPermissions("system:jiaotong:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Jiaotong jiaotong) {
        startPage();
        jiaotong.setJtRoleName(ShiroUtils.getSysUser().getUserName());
        jiaotong.setJtTitle(MyUtil.getSql(jiaotong.getJtTitle(),"jt_title"));
        jiaotong.setJtDetails(MyUtil.getSql(jiaotong.getJtDetails(),"jt_details"));
      //  jiaotongService.updateJiaotongRoleName(jiaotong);
        List<Jiaotong> list = jiaotongService.selectJiaotongList(jiaotong);
        return getDataTable(list);
    }


    /**
     * 导出交通列表
     */
    @Log(title = "交通", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:jiaotong:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Jiaotong jiaotong) {

        jiaotong.setJtTitle(MyUtil.getSql(jiaotong.getJtTitle(),"jt_title"));
        jiaotong.setJtDetails(MyUtil.getSql(jiaotong.getJtDetails(),"jt_details"));

        List<Jiaotong> list = jiaotongService.selectJiaotongList(jiaotong);
        ExcelUtil<Jiaotong> util = new ExcelUtil<Jiaotong>(Jiaotong.class);
        return util.exportExcel(list, "交通信息");
    }

    /**
     * 新增交通
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存交通
     */
    @RequiresPermissions("system:jiaotong:add")
    @Log(title = "交通", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Jiaotong jiaotong) {
        jiaotong.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(jiaotongService.insertJiaotong(jiaotong));
    }

    /**
     * 修改交通
     */
    @GetMapping("/edit/{jtId}")
    public String edit(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        if (jiaotong.getJtChangedate() != null) {
            String changedateString = formatter.format(jiaotong.getJtChangedate());
            jiaotong.setJtNewChangedate(changedateString);
        }
        mmap.put("jiaotong", jiaotong);
        return prefix + "/edit";
    }

    /**
     * 修改保存交通
     */
    @RequiresPermissions("system:jiaotong:edit")
    @Log(title = "交通", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Jiaotong jiaotong) {
        jiaotong.setUpdateBy(ShiroUtils.getLoginName());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date currentTime_2 = formatter.parse(jiaotong.getJtNewChangedate(), pos);
        jiaotong.setJtChangedate(currentTime_2);
        return toAjax(jiaotongService.updateJiaotong(jiaotong));
    }


    /**
     * 删除交通
     */
    @RequiresPermissions("system:jiaotong:remove")
    @Log(title = "交通", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(jiaotongService.deleteJiaotongByIds(ids));
    }

    /**
     * 预览交通
     */
    @GetMapping("/info/{jtId}")
    public String info(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String createdateString = formatter.format(jiaotong.getCreateTime());
        if (jiaotong.getUpdateTime() != null) {
            String updatedateString = formatter.format(jiaotong.getUpdateTime());
            jiaotong.setNewupdateTime(updatedateString);
        }
        if (jiaotong.getJtChangedate() != null) {
            String changedateString = formatter.format(jiaotong.getJtChangedate());
            jiaotong.setJtNewChangedate(changedateString);
        }
        jiaotong.setNewcreateTime(createdateString);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/info";
    }
    /**
     * 预览交通
     */
    @GetMapping("/infoFront/{jtId}")
    public String infoFront(@PathVariable("jtId") Integer jtId, ModelMap mmap,SysCategory category,String title) {



        SysCategory categoryNew = new SysCategory();

        if (category == null) {
            category = new SysCategory();
        }

        //所有的节点
        SysCategory c = new SysCategory();
        c.setParentId(100L);
        List<SysCategory> categoryList = categoryService.selectDeptList(c);

        //子目录
        List<SysCategory> childs = new ArrayList<>();

        if (category.getLevel() == null || category.getLevel() == 1) {
            if (category.getDeptId() == null) {
                categoryNew.setParentId(categoryList.get(0).getDeptId());
            } else {
                for (SysCategory n : categoryList) {
                    if (n.getDeptId() == category.getDeptId()) {
                        n.setCurr(true);
                        categoryNew.setParentId(n.getDeptId());
                    }
                }
            }
            childs = categoryService.selectDeptList(categoryNew);

        } else if (category.getLevel() == 2) {
            category = categoryService.selectDeptById(category.getDeptId());
            category.setCurr(true);
            categoryNew.setParentId(category.getParentId());
            //选中父级
            for (SysCategory n : categoryList) {
                if (n.getDeptId() == category.getParentId()) {
                    n.setCurr(true);
                }
            }
            childs = categoryService.selectDeptList(categoryNew);
            //选中子级
            for (SysCategory c1 : childs) {
                if (c1.getDeptId() == category.getDeptId()) {
                    System.out.println(c1.getDeptId() + "=="+ category.getDeptId());
                    c1.setCurr(true);
                }
            }
        }
        mmap.put("nodes", categoryList);
        mmap.put("title", title);
        mmap.put("curr", categoryNew);
        mmap.put("curr_child", category);
        mmap.put("childs", childs);


        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String createdateString = formatter.format(jiaotong.getCreateTime());
        if (jiaotong.getUpdateTime() != null) {
            String updatedateString = formatter.format(jiaotong.getUpdateTime());
            jiaotong.setNewupdateTime(updatedateString);
        }
        if (jiaotong.getJtChangedate() != null) {
            String changedateString = formatter.format(jiaotong.getJtChangedate());
            jiaotong.setJtNewChangedate(changedateString);
        }
        jiaotong.setNewcreateTime(createdateString);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/infoFront";
    }

    /**
     * 图面化
     */
    @GetMapping("/avatar/{jtId}")
    public String avatar(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/avatar";
    }

    /**
     * 保存图像
     */
    @Log(title = "图面化信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public AjaxResult updateAvatar(MultipartFile file, Jiaotong jt) {

        try {
            jt.setEditorBy(ShiroUtils.getLoginName());
            return toAjax(jiaotongService.updateJiaotongImg(jt));

        } catch (Exception e) {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 审批交通
     */
    @GetMapping("/shenpi/{jtId}")
    public String shenpi(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/shenpi";
    }

    /**
     * 审批保存交通
     */
    @Log(title = "交通", businessType = BusinessType.UPDATE)
    @PostMapping("/shenpiSave")
    @ResponseBody
    public AjaxResult shenpiSave(Jiaotong jiaotong) throws IOException {
        SysNotice notice = new SysNotice();
        notice.setNoticeType(jiaotong.getJtStatus());
        Jiaotong jt = jiaotongService.selectJiaotongById(jiaotong.getJtId());
        notice.setNoticeTitle("标题为" + "【" + jt.getJtTitle() + "】" + "的地图现势资料信息"+ "：审批通过" );
        websc.sendInfo(JSONObject.toJSONString(notice));
        return toAjax(jiaotongService.updateJiaotongShenpi(jiaotong));
    }

    /**
     * 预览交通
     */
    @GetMapping("/shenpiinfo/{jtId}")
    public String shenpiinfo(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/shenpiinfo";
    }

    /**
     * 预览图面化交通
     */
    @GetMapping("/avatarinfo/{jtId}")
    public String avatarinfo(@PathVariable("jtId") Integer jtId, ModelMap mmap) {
        Jiaotong jiaotong = jiaotongService.selectJiaotongById(jtId);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String editordateString = formatter.format(jiaotong.getEditorTime());
        jiaotong.setNeweditorTime(editordateString);
        mmap.put("jiaotong", jiaotong);
        return prefix + "/avatarinfo";
    }

    /**
     * 数据库状态
     *
     * @param type 1:交通 2：旅游 3：区划地名 4：水系 5： 综合
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Integer id, Integer status, Integer type) throws IOException {
        if (id == null || status == null || type == null) {
            return toAjax(0);
        }
        if (type == 1) {
            SysNotice notice = new SysNotice();
            notice.setNoticeType(status.toString());
            Jiaotong jt2 = jiaotongService.selectJiaotongById(id);
            notice.setNoticeTitle("标题为" + "【" + jt2.getJtTitle() + "】" + "的地图现势资料信息"+ "：被地图院数据库录用" );
            websc.sendInfo(JSONObject.toJSONString(notice));

            Jiaotong jt = new Jiaotong();
            jt.setJtId(id);
            jt.setJt_ck(status);
            return toAjax(jiaotongService.updateJiaotong(jt));
        } else if (type == 2) {
            SysNotice notice = new SysNotice();
            notice.setNoticeType(status.toString());
            Lvyou jt2 = lvyouService.selectLvyouById(id);
            notice.setNoticeTitle("标题为" + "【" + jt2.getLvTitle() + "】" + "的地图现势资料信息"+ "：被地图院数据库录用" );
            websc.sendInfo(JSONObject.toJSONString(notice));


            Lvyou lv = new Lvyou();
            lv.setLvId(id);
            lv.setJt_ck(status);
            return toAjax(lvyouService.updateLvyou(lv));
        } else if (type == 3) {
            SysNotice notice = new SysNotice();
            notice.setNoticeType(status.toString());
            Zhengqu jt2 = zhengquService.selectZhengquById(id);
            notice.setNoticeTitle("标题为" + "【" + jt2.getZqTitle() + "】" + "的地图现势资料信息"+ "：被地图院数据库录用" );
            websc.sendInfo(JSONObject.toJSONString(notice));

            Zhengqu zq = new Zhengqu();
            zq.setZqId(id);
            zq.setJt_ck(status);
            return toAjax(zhengquService.updateZhengqu(zq));
        }else if (type == 4) {
            SysNotice notice = new SysNotice();
            notice.setNoticeType(status.toString());
            Shuixi jt2 = shuixiService.selectShuixiById(id);
            notice.setNoticeTitle("标题为" + "【" + jt2.getSxTitle() + "】" + "的地图现势资料信息"+ "：被地图院数据库录用" );
            websc.sendInfo(JSONObject.toJSONString(notice));

            Shuixi sx = new Shuixi();
            sx.setSxId(id);
            sx.setJt_ck(status);
            return toAjax(shuixiService.updateShuixi(sx));
        }else if (type == 5) {
            SysNotice notice = new SysNotice();
            notice.setNoticeType(status.toString());
            Zonghe jt2 = zongheService.selectZongheById(id);
            notice.setNoticeTitle("标题为" + "【" + jt2.getZhTitle() + "】" + "的地图现势资料信息"+ "：被地图院数据库录用" );
            websc.sendInfo(JSONObject.toJSONString(notice));

            Zonghe zh = new Zonghe();
            zh.setZhId(id);
            zh.setJt_ck(status);
            return toAjax(zongheService.updateZonghe(zh));
        }

        return toAjax(0);
    }

    public static List<Map<String, Object>> map2ListbyHandler(Map respStr, String listNode) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Map map = respStr;
        String[] strArray = listNode.split(">");
        String key = null;
        Object value = null;
        for (int i = 0; i < strArray.length; i++) {
            if (map.get(strArray[i]) instanceof List) {
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    Map<String, Object> mapList = map;
                    if (((List<Map<String, Object>>) mapList.get(strArray[i])).size() > 0) {
                        for (int j = 0; j < ((List<Map<String, Object>>) mapList.get(strArray[i])).size(); j++) {
                            Map mapj = new HashMap();
                            map = ((List<Map<String, Object>>) mapList.get(strArray[i])).get(j);
                            mapj.put(strArray[i + 1], map.get(strArray[i + 1]) + "");//listNode
                            resultList.add(mapj);
                        }
                    }
                }
                break;
            } else {
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    map = (Map) map.get(strArray[i]);
                } else {
                    Map<String, Object> resultMap = new HashMap<String, Object>();
                    resultMap.put(strArray[i], map.get(strArray[i]) + "");//listNode
                    resultList.add(resultMap);
                }
            }
        }
        System.out.println("resultList >>> " + resultList);
        return resultList;
    }


    public static String interfaceUtil(String path, String data) {
        String line, resultStr = "";
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
//          conn.setRequestMethod("POST");
//           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
//            String str = "";
//            while ((str = br.readLine()) != null) {
//                System.out.println(str);
//            }

            while (null != (line = br.readLine())) {
                resultStr += line;
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
//            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    public static String load(String url, String query) throws Exception {
        URL restURL = new URL(url);
        /*
         * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");
        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);

        PrintStream ps = new PrintStream(conn.getOutputStream());
        ps.print(query);

        ps.close();

        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line, resultStr = "";

        while (null != (line = bReader.readLine())) {
            resultStr += line;
        }
        // System.out.println("3412412---"+resultStr);
        bReader.close();

        return resultStr;

    }

}
